<?php

import('com.yamvc.model.Proxy');

class BlogDataProxy extends Proxy {
	const NAME="blogDataProxy";
	/**
	 * Enter description here...
	 *
	 * @var IConnection
	 */
	private $_postsPerPage;
	private $_commentsPerPage;
	private $_tableName;
	private $_commentsTableName;
	public function __construct(){
		parent::__construct();
		$this->_postsPerPage = $this->getConfig()->get("config.model.blogDataProxy.postsPerPage",5);
		$this->_commentsPerPage = $this->getConfig()->get("config.model.blogDataProxy.commentsPerPage",5);
		$this->_tableName = $this->getConfig()->get("config.model.blogDataProxy.blogPagesTableName","sa_blog_pages");
		$this->_commentsTableName=$this->getConfig()->get("config.model.blogDataProxy.blogCommentsTableName","sa_blog_comments");
	}
	/**
	 * Enter description here...
	 *
	 * @return ResultSet
	 */
	public function getNewestPosts(){
		$stmt=$this->_connection->prepearStatement("SELECT * FROM ".$this->_tableName." ORDER BY creation_date DESC LIMIT ".$this->_postsPerPage);
		$stmt->execute();
		$res = $stmt->getResultSet();
		return $res;
	}
	
	public function getPost($postId){
		$post = $this->_connection->createTableDescriptor($this->_tableName)->createTable();
		$post->init($postId);
		return $post;
	}
	
	public function getComments($postId,$page=1){
		$stmt=$this->_connection->prepearStatement(
			"SELECT c.content as content, u.login as login, c.creation_date as date FROM ".$this->_commentsTableName." c, sa_users u WHERE c.owner_id=u.id AND c.post_id=".$postId." ORDER BY creation_date DESC LIMIT ".$page*$this->_commentsPerPage.",".$this->_commentsPerPage);
		$stmt->execute();
		return $stmt->getResultSet();
	}
	
	public function getNumberOfPages($postId){
		$stmt = $this->_connection->prepearStatement(
			"SELECT COUNT(*) as count FROM ".$this->_commentsTableName." c, sa_users u WHERE c.owner_id=u.id AND c.post_id=".$postId.";"
		);
		$stmt->execute();
		$res=$stmt->getResultSet()->next();
		if ($res==null) return 0;
		$count = (int)$res['count'];
		return round($count/$this->_commentsPerPage)+1;
	}
	
	public function addComment($userId,$postId,$data){
		$stmt = $this->_connection->prepearStatement(
			"INSERT INTO ".$this->_commentsTableName." (post_id,owner_id,content,creation_date) VALUES (".$postId.",".$userId.",'".$data."',NOW());"
		);
		try{
			$stmt->execute();
		}catch (SQLException $e){
			echo $e->getMessage();
		}
	}
}

?>